package com.ants.project.core.utils;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 上传文件
 * 下载文件
 * 目录遍历
 * 删除文件
 * Created by liushun on 2016/6/30.
 */
public class FtpUtil {

    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    private FTPClient ftp = null;

    public FtpUtil(){
        Properties properties = new Properties();
        //读取resources下面的配置
        InputStream is = FtpUtil.class.getResourceAsStream("/config.properties");
        try {
            properties.load(is);
            login(String.valueOf(properties.get("ftp.host"))
                    , Integer.parseInt(properties.get("ftp.port").toString())
                    , String.valueOf(properties.get("ftp.account"))
                    , String.valueOf(properties.get("ftp.password"))
                    ,String.valueOf(properties.get("ftp.root")));
        }catch (Exception e){
            logger.error("config.properties is no found !" + e.getMessage());
        }
    }



    public FtpUtil(String Host, int Port, String Account, String PassWord, String Root) {
        login(Host, Port, Account, PassWord, Root);
    }

    /**
     * @param Host     //主机名
     * @param Port     //端口号
     * @param Account  //账号
     * @param PassWord //密码
     * @param Root     //设置根目录
     */
    public void login(String Host, int Port, String Account, String PassWord, String Root){
        if (ftp == null) {
            ftp = new FTPClient();
            try {
                //建立连接
                ftp.connect(Host, Port);
                //登入
                ftp.login(Account, PassWord);
                //设置目录
                ftp.changeWorkingDirectory(Root);
                ftp.setControlEncoding("GBK");
                int replyCode = ftp.getReplyCode();
                ftp.setDataTimeout(120000);
                if (!FTPReply.isPositiveCompletion(replyCode)) {
                    ftp.disconnect();
                    logger.error("FTP server refused connection.");
                }else
                    System.err.println(Host + " login success !");
            } catch (IOException e) {
                logger.error("登录ftp服务器 " + Host + " 失败,连接超时！" + e.getMessage());
                this.ftp = null;
            }
        }
    }

    /**
     * 遍历目录
     *
     * @param folder 目录
     * @return
     */
    public List<FTPFile> loooFile(String folder) {
        List list = null;
        try {
            list = new ArrayList();
            if (folder != null)
                ftp.changeWorkingDirectory(folder);
            FTPFile[] ftpFiles = ftp.listFiles();
            for (FTPFile file : ftpFiles)
                list.add(file);
        } catch (IOException e) {
            logger.error("FTP > 连接失败!" + e.getMessage());
            this.ftp = null;
        }
        return list;
    }

    /**
     * 上传文件到ftp
     *
     * @param fileName 本地文件路径
     * @param newName  服务器新名称
     * @param folder   文件夹目录
     * @return
     */
    public boolean upload(String fileName, String newName, String folder) {
        File file = new File(fileName);
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            if (folder != null)
                ftp.changeWorkingDirectory(folder);
            ftp.setBufferSize(1024);
            ftp.setControlEncoding("utf-8");
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.storeFile(newName, fileInputStream);
        } catch (Exception e) {
            logger.error("FTP > 上传文件失败!" + e.getMessage());
            this.ftp = null;
        }
        return false;
    }

    public boolean upload(String fileName, String folder) {
        String newName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
        return upload(fileName, newName, folder);
    }

    public boolean upload(String fileName) {
        String newName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
        return upload(fileName, newName, null);
    }


    /**
     * 删除文件
     *
     * @param fileName 文件名名称
     * @param folder   文件目录为默认为根目录
     * @return
     */
    public boolean deleteFile(String fileName, String folder) {
        try {
            if (folder != null)
                ftp.changeWorkingDirectory(folder);
            ftp.deleteFile(fileName);
        } catch (IOException e) {
            logger.error("FTP > 删除文件异常!" + e.getMessage());
            return false;
        }
        return true;
    }

    public boolean deleteFile(String fileName) {
        return deleteFile(fileName, null);
    }

    /**
     * 删除空目录
     */
    public boolean deleteFolder(String folder) {
        try {
            ftp.removeDirectory(folder);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return false;
        }
        return true;
    }


    public boolean download(String folder, String ftpFile) {
        try {
            boolean b = ftp.changeWorkingDirectory(ftpFile);
            if (b) {
                FTPFile[] ftpFiles = ftp.listFiles();
                for (FTPFile f : ftpFiles) {
                    String fileName = f.getName();
                    File fo = new File(folder + ftpFile);
                    if (!fo.exists())
                        fo.mkdir();
                    File file = new File(folder + ftpFile + "/" + fileName);
                    ftp.retrieveFile(fileName, new FileOutputStream(file));
                    logger.info(fileName + " download success ~~");
                }
            } else {
                File file = new File(folder + File.separator + ftpFile);
                ftp.retrieveFile(ftpFile, new FileOutputStream(file));
                logger.info(ftpFile + " download success ~~");
            }
        } catch (Exception e) {
            logger.error("FTP > 文件下载失败!" + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 关闭链接
     */
    public void colse() {
        try {
            ftp.disconnect();
        } catch (IOException e) {
            logger.error("FTP > 关闭连接出现异常!" + e.getMessage());
        }
    }
}
